import { useAreaStore } from "@/store";
import type { AreaLevel, CascadedAreaItem, NullableAreaModel } from "@/types";
import { isString } from "@/utils";
import { Cascader, Form } from "@arco-design/web-react";
import { useEffect, useMemo, useState } from "react";

interface SelectAreaProps {
	id?: string;
	value?: NullableAreaModel;
	/** 显示级别 */
	level?: AreaLevel;
	placeholder?: string;
	/** 选择即改变 */
	changeOnSelect?: boolean;
	disabled?: boolean;
	onChange?: (model: NullableAreaModel) => void;
}

export default function SelectArea({
	id,
	value,
	level = "city",
	placeholder = "请选择地区",
	changeOnSelect = false,
	disabled = false,
	onChange,
}: SelectAreaProps) {
	const { getData: getAreas } = useAreaStore();
	const [data, setData] = useState<CascadedAreaItem[]>([]);

	const { disabled: formDisabled } = Form.useFormContext();
	const mergedDisabled = disabled !== undefined ? disabled : formDisabled;

	useEffect(() => {
		getAreas().then(setData);
	}, [getAreas]);

	const handleChange = (value: (string | string[])[]) => {
		if (value.length === 0) {
			onChange?.({});
			return;
		}
		const v = isString(value[0]) ? (value as string[]) : value[0];
		const model: NullableAreaModel = {
			province: v[0] ?? "",
			city: v[1] ?? "",
			county: v[2] ?? "",
		};
		onChange?.(model);
	};

	const initialValue = useMemo(() => {
		if (!value) return [];
		if (level === "province") return [value.province ?? ""];
		if (level === "city") return [value.province ?? "", value.city ?? ""];
		return [value.province ?? "", value.city ?? "", value.county ?? ""];
	}, [value, level]);

	const options = useMemo(() => {
		if (level === "province")
			return data.map((i) => ({ ...i, children: undefined }));
		if (level === "city")
			return data.map((i) => ({
				...i,
				children: i.children?.map((j) => ({ ...j, children: undefined })),
			}));
		return data;
	}, [data, level]);

	return (
		<Cascader
			id={id}
			fieldNames={{ label: "name", value: "code", children: "children" }}
			value={initialValue}
			options={options}
			placeholder={placeholder}
			disabled={mergedDisabled}
			onChange={handleChange}
			changeOnSelect={changeOnSelect}
		/>
	);
}
